<template>
  <div class="fx-checkbox-button"
       :class="[{active:handleActive(checkboxGroupValue),disabled:handleDisabled(checkboxGroupValue)},checkboxGroupSize]"
       @click="checkboxClick(checkboxGroupValue)">
    <input type="checkbox" hidden :name="handleActive(checkboxGroupValue)">
    <slot>{{ label }}</slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject, PropType } from 'vue'
import { Emitter } from 'mitt'

interface CheckboxProps {
  disabled: boolean,
  label: string
}

export default defineComponent({
  name: 'FCheckboxButton',
  props: {
    // 禁用
    disabled: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 选项
    label: {
      type: String as PropType<string>,
      default: ''
    }
  },
  setup (props: CheckboxProps) {
    // 获取当前 checkboxGroup 选中数据集
    const checkboxGroupValue = inject<string[]>('checkboxGroupValue', [])
    // 获取当前 checkboxGroup 禁用
    const checkboxGroupDisabled = inject<boolean>('checkboxGroupDisabled', false)
    // 获取当前 checkboxGroup 选中个数限制
    type CheckboxNumberProps = { max: number, min: number } | undefined
    const checkboxGroupNumber = inject<CheckboxNumberProps>('checkboxGroupNumber', undefined)
    // 获取当前 checkboxGroup 大小
    const checkboxGroupSize = inject<string>('checkboxGroupSize', 'default')
    // 获取checkboxGroup 传数据
    const checkboxGroupMittEmit = inject<Emitter['emit'] | undefined>('checkboxGroupMittEmit', undefined)
    // 处理选中样式
    const handleActive = (arr: string[]): boolean => {
      // 根据选中的数组 显示选中状态
      return arr.some((item: string) => item === props.label)
    }
    // 处理禁用样式
    const handleDisabled = (arr: string[]): boolean => {
      // 禁用状态
      let isMaxMin = false
      // 如果存在父组件的列表数据  并且存在选中个数限制
      if (arr && arr.length && checkboxGroupNumber) {
        isMaxMin = arr.length >= checkboxGroupNumber.max || arr.length < checkboxGroupNumber.min
        // 将非选中状态显示可点状态
        isMaxMin = isMaxMin && !handleActive(arr)
      }
      return checkboxGroupDisabled || props.disabled || isMaxMin
    }
    // 多选框点击
    const checkboxClick = (arr: string[]): void => {
      if (props.disabled || checkboxGroupDisabled || handleDisabled(arr)) return
      if (checkboxGroupMittEmit && checkboxGroupValue) {
        checkboxGroupMittEmit('checkboxMitt', props.label)
      }
    }

    return {
      checkboxGroupValue,
      checkboxGroupSize,
      checkboxGroupDisabled,
      handleActive,
      handleDisabled,
      checkboxClick
    }
  }
})
</script>
